function addRippleEffect(o) {
    o.classList.add("__pyui_ripple")
    o.addEventListener("click", function (e) {
        // Create span element
        let ripple = document.createElement("span");

        // Add ripple class to span
        // ripple.classList.add("ripple");

        // Add span to the button
        o.appendChild(ripple);

        // Get position of X
        let x = e.clientX - e.currentTarget.offsetLeft;

        // Get position of Y
        let y = e.clientY - e.currentTarget.offsetTop;

        // Position the span element
        ripple.style.left = `${x}px`;
        ripple.style.top = `${y}px`;

        // Remove span after 0.3s
        setTimeout(() => {
            ripple.remove();
        }, 300);
    })
}
function choice(arr) {
    var idx = parseInt(Math.floor(Math.random() * arr.length))
    return arr[idx]
}
function randomNum() {
    var v = Math.random()
    while (v < 0.1) v = v * 10;
    let s = choice([10, 100])
    v = v * s
    // arr = [0, 10, 100]
    var zheng = parseInt(Math.floor(v))
    var vv = choice([0, 1, 2])
    if (s == 100) vv = choice([0, 1])
    if (vv == 0) v = zheng;
    else {
        v = parseFloat(v.toFixed(vv))
    }
    return v

}
function getQ() {
    var a = randomNum()
    var b = randomNum()
    var op = Math.random()
    var ans = 0
    if (op < 0.25) {
        return [a, "+", b, a + b]
    } else if (op < 0.5) {
        if (a > b) return [a, "-", b, a - b]
        else return [b, "-", a, b - a]
    } else if (op < 0.75) {
        return [a, "×", b, a * b]
    } else {
        if (("" + b).length >= 4) b = parseInt(b)
        return [a, "÷", b, a / b]
    }
}
function DownLoadImg(content) {
    // 格式
    var imageType = 'png';
    // 文件名
    var fileName = Date.now();
    var raw = window.atob(content);
    var rawLength = raw.length;
    var uInt8Array = new Uint8Array(rawLength);
    for (var i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
    }
    var blob = new Blob([uInt8Array], { type: 'image/' + imageType });
    var aLink = document.createElement('a');
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("click", true, true);
    aLink.download = fileName;
    aLink.href = URL.createObjectURL(blob);
    aLink.click();
}
const canvas = document.querySelector("canvas");
const signature = new SmoothSignature(canvas);
const tips = document.getElementById("tips")
const input = document.getElementById("input")
const Q = document.getElementById("q")
const IDX = document.getElementById("idx")
const container = document.getElementById("container")
var ans = 0
var cnt = 0
const history = []
// 生成JPG
function exportPic() {
    var d = new Date();
    var now = `${d.getFullYear()}-${(d.getMonth() + 1)}-${d.getDate()} ${d.getHours()}:${d.getMinutes()}`
    var out = `<div><div class="reportTitle">已打卡</div><div class="reportTime">${now}</div></div><div class="reportContent">`
    for (var i = 0; i < history.length; ++i) {
        let qitem = history[i]
        var item = `<div> ${qitem}  </div>`
        out += item;
    }
    out = out + "</div>"
    container.innerHTML = `<div id="report" class="card"  >${out}</div>`;

    function toPic() {
        html2canvas(document.getElementById("report"), {
            onrendered: function (canvas) {
                // 创建一个canvas
                // document.body.appendChild(canvas);
                var dataUrl = canvas.toDataURL("image/jpeg", 1.0);
                // var img = document.createElement("img")
                // img.src = dataUrl
                // img.style.width = 300 + "px";
                // img.style.margin = "0 auto"
                // container.innerHTML = "";
                // container.appendChild(img)
                DownLoadImg(dataUrl.replace("data:image/jpeg;base64,", ""))
            },
        });
    }
    document.getElementById("report").onclick = function () {
        toPic();
    }
}
function nextQ(check) {
    if (check) {
        var user = parseFloat(input.value);
        var diff = user - ans;
        if (diff != 0) {
            tips.innerHTML = "计算错误，请重新计算！" + diff
            return;
        }
        var q = Q.innerHTML + ans;
        // var caogao = signature.getJPG()
        // history.push([q, caogao])
        history.push(q)
        console.log(history.length)
        if (history.length >= 10) {
            exportPic()
        }
    }
    cnt += 1;
    IDX.innerHTML = cnt;

    signature.clear();
    input.value = ""
    let arr = getQ();
    ans = parseFloat(arr[3].toFixed(3))
    input.value = ans
    Q.innerHTML = arr[0] + arr[1] + arr[2] + " =  "
}
function init() {
    nextQ(false)
    var btns = document.getElementsByTagName("button");
    for (var i = 0; i < btns.length; ++i) {
        let btn = btns[i];
        addRippleEffect(btn)
        btn.onclick = function () {
            let id = btn.getAttribute("id");
            if (id == "clearBtn") {
                signature.clear();
                input.text = "";
                tips.innerHTML = ""
            } else if (id == "undoBtn") {
                signature.undo()
            } else if (id == "nextBtn") {
                nextQ(true);
            }
        }
    }
}

init();